package com.net.xpay.admin.controller.common;

import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.util.NetUtil;
import com.net.xpay.common.domain.CheckCode;
import com.net.xpay.common.domain.admin.rbac.AdminUser;
import com.net.xpay.common.enums.user.CheckCodeType;
import com.net.xpay.common.manager.admin.rbac.AdminUserManager;
import com.net.xpay.common.service.CheckCodeService;
import com.net.xpay.core.constant.PoseidonErrorCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
  on 08/02/2018.
 */
@RestController
@RequestMapping("/common/check-code")
@Api(tags = "公共/验证码", description = "公共 验证码 net")
@Slf4j
public class AdminCheckCodeController {

    @Autowired
    private CheckCodeService checkCodeService;
    @Autowired
    private AdminUserManager adminUserManager;



    @ApiOperation("获取登录验证码")
    @GetMapping("/login")
    @ApiImplicitParam(name = "mobile", value = "手机号")
    public ResultData<Boolean> getLoginCheckCode(HttpServletRequest request, String mobile) {
        if (Strings.isNullOrEmpty(mobile)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "手机号不能为空");
        }
        AdminUser user = adminUserManager.findByMobile(mobile);
        if (user == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "该手机号尚未注册");
        }
        return new ResultData<>(sendCheckCodeForMobile(request, mobile, CheckCodeType.ADMIN_LOGIN));
    }

    @ApiOperation("获取修改手机号验证码")
    @GetMapping("/modify-mobile")
    @ApiImplicitParam(name = "mobile", value = "手机号")
    public ResultData<Boolean> getRegisterCheckCode(HttpServletRequest request,String mobile) {
        return new ResultData<>(sendCheckCodeForMobile(request, mobile, CheckCodeType.MODIFY_MOBILE));
    }

    private boolean sendCheckCodeForMobile(HttpServletRequest request, String mobile, CheckCodeType checkCodeType) {
        CheckCode checkCode = checkCodeService.sendCheckCode(mobile, checkCodeType, NetUtil.getRequestRealIp(request));
        return checkCode != null && !Strings.isNullOrEmpty(checkCode.getCode());
    }
}
